<template>
  <div>
    <el-form :model="form" :rules="rules" label-width="120px" ref="ruleFormRef">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >提交</el-button
        >
        <el-button type="primary" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref } from "vue";
import { login } from "../request/api";
import { LoginData } from "../type/login";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
export default defineComponent({
  setup() {
    const data = reactive(new LoginData());
    const rules = {
      username: [
        {
          required: true,
          message: "请输入用户名",
          trigger: "blur",
        },
        {
          min: 3,
          max: 8,
          message: "Length should be 3 to 8",
          trigger: "blur",
        },
      ],
      password: [
        {
          required: true,
          message: "请输入密码",
          trigger: "blur",
        },
        {
          min: 3,
          max: 12,
          message: "Length should be 3 to 12",
          trigger: "blur",
        },
      ],
    };

    const ruleFormRef = ref<FormInstance>();
    const Router = useRouter();
    const submitForm = async (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      await formEl.validate((valid) => {
        if (valid) {
          login(data.form).then((res) => {
            if (res.data.msg == "登录成功") {
              localStorage.setItem("token", res.data.token);
              // $msgbox("登录成功")
              ElMessage({
                message: "登录成功",
                type: "success",
              });
              Router.push("/home");
            } else{
              ElMessage.error("用户名或密码错误")
            }
          });
        } else {
          console.log("error submit!");
        }
      });
    };
    const resetForm = () => {
      data.form = {
        username:"",
        password:""
      }
    };

    return { ...toRefs(data), rules, submitForm, resetForm, ruleFormRef };
  },
});
</script>

<style scoped>
</style>